package com.wxg.jfinal.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.c3p0.C3p0Plugin;

public class JFinalGenUtils {
	
	public static final String PRO_FILE = "jfinal/main.properties";
	public static final String PRO_FILE_SQLITE = "jfinal/englishword_sqlite.properties";
	
	public static final String PROJECT = "${project}";
	public static final String OUTPUT_DIR = "outputDir";
	public static final String PKG_NAME = "pkgName";
	
//	private static Prop prop;
	
	private static Map<String,String> prop;
	
	private JFinalGenUtils(){}
	
	/**
	 * 加载配置文件. `PropKit.use`会丢失反斜线
	 * 
	 * <http://git.oschina.net/jfinal/jfinal/issues/200>
	 * 在JFinal上提交了一个Issue
	 * @return
	 */
	public static Map<String,String> loadProperties(){
		return loadProperties(PRO_FILE_SQLITE);
	}
	
	/**
	 * 
	 * @param config
	 * @return
	 */
	public static Map<String,String> loadProperties(String config){
		Map<String,String> map = new HashMap<String,String>();
		try {
			BufferedReader br = null;
			try {
				InputStream is = JFinalGenUtils.class.getClassLoader().getResourceAsStream(config);
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String line = null;
				
				while( (line=br.readLine()) != null ){
					if(!line.startsWith("#") && StringUtils.isNotBlank(line)){
						String[] arr = line.split("=");
						map.put(arr[0].trim(), arr[1].trim());
					}
				}
			} finally {
				if(null != br){
					br.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	static {
//		prop = PropKit.use(PRO_FILE);
//		prop = PropKit.use("jfinal/main.conf");
		prop = loadProperties();
	}
	
	public static C3p0Plugin getC3p0Plugin(){
		C3p0Plugin c3p0Plugin = new C3p0Plugin(prop.get("db_url"), 
				prop.get("db_username"), prop.get("db_password"));
		return c3p0Plugin;
	}
	
	public static DataSource getDataSource() {
		C3p0Plugin c3p0Plugin = getC3p0Plugin();
		c3p0Plugin.start();
		return c3p0Plugin.getDataSource();
	}
	
	/**
	 * ${project} : 表示使用使用"PathKit.getWebRootPath()"作为根目录
	 * "/src/main/java" : 是Maven工程的目录结构,若是其他环境需要修改
	 * --
	 * pkgName : 配置文件中的key,表示包名
	 * outputDir : 配置文件中的key,表示输出目录
	 * --
	 * modelPkg, modelOutputdir, basePkg, baseOutputdir 见名之意,略
	 * 
	 * @return
	 */
	public static Map<String,String> prepare(){
		Map<String,String> map = new HashMap<String,String>();
		
		// F:\wxg\Git\FromHk\DruidStudy
		String _RootPath = PathKit.getWebRootPath();
		
		String modelPkg = prop.get("pkgName");
		String modelOutputdir = prop.get("outputDir");
		String basePkg = modelPkg + ".base";
		String baseOutputdir = "";
		
		if("${project}".equals(modelOutputdir)){
			modelOutputdir = _RootPath + "/src/main/java/" + modelPkg.replaceAll("\\.", "/");
		}else{
			modelOutputdir = modelOutputdir.replaceAll("\\\\", "/");
			if(!modelOutputdir.endsWith("/")){
				modelOutputdir = modelOutputdir + "/";
			}
			modelOutputdir = modelOutputdir + modelPkg.replaceAll("\\.", "/");
		}
		baseOutputdir = modelOutputdir + "/base";
		
		map.put("modelPkg", modelPkg);
		map.put("modelOutputdir", modelOutputdir);
		map.put("basePkg", basePkg);
		map.put("baseOutputdir", baseOutputdir);
		
		map.put("dialect", prop.get("dialect"));
		map.put("tablePrefix", prop.get("tablePrefix"));
		
		return map;
	}
	
	/**
	 * 调用这个方法就生产JFinal的对象
	 * 
	 * 这里面的有些配置也是可以移到配置文件中去的，但是我现在暂时没有这样做！（时间成本）
	 * 
	 * Add at 2017年5月11日17:19:34
	 * 1. 配置文件中设置"方言"
	 * 2. 配置文件中设置"前缀"
	 * 
	 */
	public static void gen(){
		Map<String,String> map = prepare();
		Generator gen = new Generator( getDataSource(),
				map.get("basePkg"), map.get("baseOutputdir"),
				map.get("modelPkg"), map.get("modelOutputdir"));
		// 设置方言
//		gen.setDialect( new JFinalDialect().d(map.get("dialect")) );
		gen.setDialect( new MysqlDialect() );
		//添加不需要生成的表名
//		gen.addExcludedTable("");
		// 设置是否在 Model 中生成 dao 对象
		gen.setGenerateDaoInModel(true);
		// 设置是否生成字典文件
		gen.setGenerateDataDictionary(false);
		// 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user"，移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
		String[] arr = map.get("tablePrefix").split(",");
		String[] arr2 = new String[arr.length];
		for(int i=0;i<arr.length;i++){
			arr2[i] = arr[i].trim();
		}
		gen.setRemovedTableNamePrefixes( arr2 );
		// 生成
		gen.generate();
	}
	
	public static void setProp(Map<String, String> prop) {
		JFinalGenUtils.prop = prop;
	}
}
